import { useEffect, useMemo, useState } from "react";
const initConfig = {
  total: 60,
  text: "获取验证码",
  wait: 1000, // 时间间隔
  getText: (n: number) => {
    return n + " s";
  },
};
type Config = Partial<typeof initConfig>;
export function useCodeCountDown(_config: Config = initConfig) {
  const config = {
    ...initConfig,
    ..._config,
  };
  let [text, setText] = useState(config.text);
  let constObj = useMemo(() => {
    return {
      timer: null,
      startTime: 0,
      running: false,
    };
  }, []);

  useEffect(() => {
    return stop;
  }, []);
  let handler = () => {
    constObj.startTime--;

    if (constObj.startTime <= 0) {
      stop();
    } else {
      run(constObj.startTime);
    }
  };
  let stop = () => {
    constObj.running = false;
    setText(config.text);
    clearInterval(constObj.timer);
  };
  let run = (time: number) => {
    setText(config.getText(time));
  };
  return {
    text,
    run() {
      if (constObj.running) return;
      constObj.running = true;
      constObj.startTime = config.total + 1;
      handler();
      constObj.timer = setInterval(handler, config.wait);
    },
    stop,
  };
}
